'use strict';

if (zxcv && !zxcv.raw.Texture2D) {
    if (window.WebGLRenderingContext) {
        zxcv.raw.Texture2D = function (uri, onload, onerror) {
            var self = this,
                gl = zxcv.raw.graphics.gl,
                image;

            this.width  = 0;
            this.height = 0;
            this.status = zxcv.ASSET_LOADING;

            image = new Image();
            this.raw = null;
            image.onload = function () {                
                var texture = gl.createTexture();
                gl.bindTexture(gl.TEXTURE_2D, texture);
                gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
                gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this);
                gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
                gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
                gl.bindTexture(gl.TEXTURE_2D, null);
                self.width  = this.width;
                self.height = this.height;
                self.raw    = texture;
                self.status = zxcv.ASSET_LOADED;
                this.src   = null;

                if (onload)
                    onload.call(self);
            };
            image.onerror = function () {
                self.status = zxcv.ASSET_NOT_FOUND;
                
                if (onerror)
                    onerror.call(self);
            };
            image.src = uri;
        };
        
        zxcv.raw.Texture2D.prototype.unload = function () {
            this.status = zxcv.ASSET_UNLOADED;
            if (this.texture)
                zxcv.raw.graphics.gl.deleteTexture(this.texture);

            delete this.raw;
        };
    }
    else {
        zxcv.raw.Texture2D = function (uri, onload, onerror) {
            var self = this;

            this.width  = 0;
            this.height = 0;
            this.status = zxcv.ASSET_LOADING;

            this.raw = new Image();
            this.raw.onload = function () {
                self.width  = this.width;
                self.height = this.height;
                self.status = zxcv.ASSET_LOADED;
                
                if (onload)
                    onload.call(self);
            };
            this.raw.onerror = function () {
                self.status = zxcv.ASSET_NOT_FOUND;
                
                if (onerror)
                    onerror.call(self);
            };
            this.raw.src = uri;
        };

        zxcv.raw.Texture2D.prototype.unload = function () {
            this.status  = zxcv.ASSET_UNLOADED;
            this.raw.src = null;
            
            delete this.raw;
        };
    }
}